package com.stevin.tool;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author mars
 * @date 2019/02/02
 */
@Slf4j
public class MagnetParseTool {

    public static class VIP {
        public static List<String> parse(String name) {
            try {
                String content = parseVip(name);
                return findAllVipMagnetKey(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private static String parseVip(String name) throws IOException {
            String url = "http://nanrenvip.cc/nvyouku/" + name + ".html";
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .followRedirects(false)
                    .followSslRedirects(false)
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .hostnameVerifier((hostname, session) -> true)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()//默认就是GET请求，可以不写
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            return new String(body.bytes());
        }

        private static Pattern vipKeyPattern = Pattern.compile("<a(.*) href=\".*(.*)>.*<\\/a>");

        private static List<String> findAllVipMagnetKey(String content) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
            String line;
            List<String> magnetList = Lists.newArrayList();
            while ((line = reader.readLine()) != null) {
                Matcher matcher = vipKeyPattern.matcher(line);
                if (matcher.find()) {
                    String result = matcher.group();
                    if (!result.contains("fanhaoku")) {
                        continue;
                    }
                    String codeUrl = result.split(" +")[1];
                    if (codeUrl.contains(">")) {
                        String magnetKey = codeUrl.split(">")[1];
                        magnetList.add(magnetKey);
                        log.info("add magnetKey:{}", magnetKey);
                    }
                }
            }
            return magnetList;
        }
    }

    static class SeesaaWiki {

        public static List<String> parse(String decodeName) {
            try {
                String content = parseSeesaaWiki(decodeName);

                return findAllSeesaaWikiMagnetKey(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private static String parseSeesaaWiki(String decodeName) throws IOException {
            String url = "https://seesaawiki.jp/av_neme/d/" + decodeName;

            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .followRedirects(false)
                    .followSslRedirects(false)
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .hostnameVerifier((hostname, session) -> true)
                    .build();

            final Request request = new Request.Builder()
                    .url(url)
                    .get()//默认就是GET请求，可以不写
                    .build();
            Response response = okHttpClient.newCall(request).execute();

            ResponseBody body = response.body();
            return new String(body.bytes());
        }

        private static Pattern seesaaKeyPattern = Pattern.compile("[a-zA-z]+://(www.mgstage.com)[^\\s]*[0-9a-zA-Z](-)[0-9]{2,5}");
        private static Pattern seesaaKeyPattern2 = Pattern.compile("[a-zA-z]+://(pics.dmm.co.jp)[^\\s]*[0-9a-zA-Z][0-9]{2,5}");
        private final static Pattern seesaaKeyPattern3 = Pattern.compile("([a-zA-Z]){2,5}(-)[0-9]{2,5}");


        private static List<String> findAllSeesaaWikiMagnetKey(String content) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
            String line;
            List<String> magnetList = Lists.newArrayList();
            while ((line = reader.readLine()) != null) {
                Matcher matcher = seesaaKeyPattern.matcher(line);
                if (matcher.find()) {
                    String result = matcher.group();
                    String magnetUrl = result.split("www.mgstage.com/")[1];
                    if (magnetUrl.contains("/")) {
                        String url = magnetUrl.split("/")[3];
                        magnetList.add(url);
                        log.info("add magnetUrl:{}", url);
                    }
                }
                Matcher matcher2 = seesaaKeyPattern2.matcher(line);
                if (matcher2.find()) {
                    String result = matcher2.group();
                    String magnetUrl = "";
                    if (result.contains("pics.dmm.co.jp/digital/")) {
                        magnetUrl = result.split("pics.dmm.co.jp/digital/")[1];
                    }
                    if (result.contains("pics.dmm.co.jp/mono/movie/")) {
                        magnetUrl = result.split("pics.dmm.co.jp/mono/movie/")[1];
                    }
                    if (magnetUrl.contains("/")) {
                        String url = magnetUrl.split("/")[2];
                        magnetList.add(url);
                        log.info("add magnetUrl:{}", url);
                    }
                }
            }

            return magnetList.stream()
                    .map(m -> {
                        if (m.contains("NTK") || m.contains("ARA") || m.contains("MAAN") || m.contains("MIUM") || m.contains("LUXU")) {
                            return m;
                        }
                        if (m.contains("00") && !m.contains("-")) {
                            if (m.contains("0000")){
                                m = m.replace("0000", "-00");
                            }else {
                                m = m.replace("00", "-");
                            }
                        }
                        Matcher matcher = seesaaKeyPattern3.matcher(m);
                        if (matcher.find()) {
                            return matcher.group();
                        }
                        return m;
                    })
                    .map(m-> {
                        log.info("print magnetUrl:{}",m);
                        return m;
                    })
                    .distinct().collect(Collectors.toList());
        }
    }

    static class Mgshd {

        public static List<String> parse(int pageId, String type) {
            try {
                List<String> magnet = new ArrayList<>();
                for (int i = 1; i <= pageId; i++) {
                    String content = parseMgshd(i, type);
                    List<String> allMgshdMagnetKey = findAllMgshdMagnetKey(content);
                    magnet.addAll(allMgshdMagnetKey);
                }

                return magnet;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            return null;
        }

        private static String parseMgshd(int pageId, String type) throws IOException {
            String url = "http://www.mgshd.net/" + type;
            if (pageId > 1) {
                url = "http://www.mgshd.net/" + type + "/page/" + pageId;
            }
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .followRedirects(false)
                    .followSslRedirects(false)
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .hostnameVerifier((hostname, session) -> true)
                    .build();

            final Request request = new Request.Builder()
                    .url(url)
                    .get()//默认就是GET请求，可以不写
                    .build();
            Response response = okHttpClient.newCall(request).execute();

            ResponseBody body = response.body();
            return new String(body.bytes());
        }


        private static Pattern mgshdKeyPattern = Pattern.compile("[a-zA-z]+://(www.mgshd.net)[^\\s]*[0-9a-zA-Z](-)[0-9]{2,5}");

        private static List<String> findAllMgshdMagnetKey(String content) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
            String line;
            List<String> magnetList = Lists.newArrayList();
            while ((line = reader.readLine()) != null) {
                Matcher matcher = mgshdKeyPattern.matcher(line);
                if (matcher.find()) {
                    String result = matcher.group();
                    if (result.contains("wp-content")) {
                        continue;
                    }
                    String magnetUrl = result.split("http://www.mgshd.net/")[1];
                    magnetList.add(magnetUrl);
                    log.info("add magnetUrl:{}", magnetUrl);
                }
            }
            return magnetList.stream().distinct().collect(Collectors.toList());
        }
    }

    static class RenRenCili {
        public static List<String> parse(String content) {
            List<String> magnets = new ArrayList<>();
            List<String> renRenCiliUrls = findAllRenRenCiliUrl(content);
            for (String url : renRenCiliUrls) {
                String magnet = parseRenRenCili(url);
                if (!Strings.isNullOrEmpty(magnet)) {
                    magnets.add(magnet);
                }
            }
            return magnets;
        }

        private static String parseRenRenCili(String urlSuffix) {
            String url = "https://www.bturl.at" + urlSuffix;
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .followRedirects(false)
                    .followSslRedirects(false)
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .hostnameVerifier((hostname, session) -> true)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()//默认就是GET请求，可以不写
                    .build();
            Response response;
            try {
                TimeUnit.SECONDS.sleep(1);
                response = okHttpClient.newCall(request).execute();
                ResponseBody body = response.body();
                return new String(body.bytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

      //  private static Pattern renRenKeyPattern = Pattern.compile("<a href='/(magnet).*>");
      private static Pattern renRenKeyPattern = Pattern.compile("<a target=\"_blank\" href=.*>");

        private static List<String> findAllRenRenCiliUrl(String content) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
            String line;
            List<String> magnetList = Lists.newArrayList();
            try {
                while ((line = reader.readLine()) != null) {
                    Matcher matcher = renRenKeyPattern.matcher(line);
                    if (matcher.find()) {
                        String result = matcher.group();
                        String suffix = result.split("\"")[3];
                        if (magnetList.contains(suffix)) {
                            continue;
                        }
                        magnetList.add(suffix);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return magnetList;
        }
    }

}
